package com.pig4cloud.pig.module.controller.setMeal;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.OrderUtil;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.location.City;
import com.pig4cloud.pig.module.api.entity.location.Province;
import com.pig4cloud.pig.module.api.entity.setMeal.SetMeal;
import com.pig4cloud.pig.module.service.location.CityService;
import com.pig4cloud.pig.module.service.location.ProvinceService;
import com.pig4cloud.pig.module.service.setMeal.ISetMealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 套餐列Controller
 *
 * @author ruoyi
 * @date 2022-06-06
 */
@Validated
@Api(value = "套餐列控制器", tags = {"套餐列管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/meal")
public class SetMealController {

    private final ISetMealService setMealService;
	private final ProvinceService provinceService;
	private final CityService cityService;

//	@Value("${ruoyi.imgUrl}")
//	private String imgUrl;

	@Value("${ruoyi.imgUrlOss}")
	private String imgUrlOss;

	@Value("${ruoyi.profile}")
	private String uploadPath;
    /**
     * 查询套餐列列表
     */
    @ApiOperation("查询套餐列列表")
    @PreAuthorize("@pms.hasPermission('module:meal:list')")
    @GetMapping("/list")
    public TableDataInfo<SetMeal> list(@Validated SetMeal setMeal) {
        QueryWrapper<SetMeal> qw = new QueryWrapper<>();

        TableDataInfo<SetMeal> td = PageUtils.buildDataInfo(setMealService.page(PageUtils.buildPage(),qw));
        List<SetMeal> list = td.getData();
        return td;
    }

    /**
     * 获取套餐列详细信息
     */
    @ApiOperation("获取套餐列详细信息")
    @PreAuthorize("@pms.hasPermission('module:meal:query')")
    @GetMapping("/{id}")
    public R<SetMeal> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        SetMeal setMeal = setMealService.getById(id);
		if(setMeal!=null){
			if(setMeal.getProvId()!=null && setMeal.getCityId()!=null){
				String[] areas = { setMeal.getProvId()+"",setMeal.getCityId()+""};
				setMeal.setProvinceArray(areas);
			}
		}
        return R.ok(setMeal);
    }

    /**
     * 新增套餐列
     */
    @ApiOperation("新增套餐列")
    @PreAuthorize("@pms.hasPermission('module:meal:add')")
    @SysLog("套餐列")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody SetMeal setMeal) {

		String mealNo = OrderUtil.getSetMealNo();
		setMeal.setMealNo(mealNo);


		if(setMeal.getProvinceArray()!=null&&setMeal.getProvinceArray().length==2){
			setMeal.setProvId(Integer.parseInt(setMeal.getProvinceArray()[0]));
			setMeal.setCityId(Integer.parseInt(setMeal.getProvinceArray()[1]));

			Province province = provinceService.findById(setMeal.getProvinceArray()[0]);
			if(province!=null){
				setMeal.setProvName(province.getProvinceName());
			}

			City city = cityService.findById(setMeal.getProvinceArray()[1]);
			if(city!=null){
				setMeal.setCityName(city.getCityName());
			}
		}


		try{
			String qrCode = "";
			String content = "https://www.sdyuedou.com/wxmini/meal/getMeal?no=" + mealNo;
			String fileName = "mer_qr_" + mealNo + ".jpg";

			int upload_type = 0;//FileUploadUtils.TYPE_SET_MEAL;
			System.out.println("content:  "+ content);
			String img_key = ""; // FileUploadUtils.getUploadPrefix(upload_type) + fileName;
			QRCodeUtilEx.createQrCodeImg(content,mealNo, null, uploadPath +"/"+img_key, true, fileName, upload_type);
			qrCode = img_key;
			setMeal.setQrCode(qrCode);
		}catch (Exception e){
			e.printStackTrace();
		}

        return R.okByRow(setMealService.save(setMeal) ? 1 : 0);
    }


	/**
	 * 重置二维码
	 */
	@SysLog("重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@pms.hasPermission('module:meal:edit')")
	public R<Void> resetQrCode(@RequestBody SetMeal setMeal) {
		if(setMeal.getId()!=null){
			try{
				setMeal = setMealService.getById(setMeal.getId());
				if(setMeal != null){
					String qrCode = "";
					String content = "https://www.sdyuedou.com/wxmini/meal/getMeal?no=" + setMeal.getMealNo();
					String fileName = "meal_qr_" + setMeal.getMealNo() + ".jpg";

					int upload_type = 0;//FileUploadUtils.TYPE_SET_MEAL;
					System.out.println("content:  "+ content);
					String img_key = "";//FileUploadUtils.getUploadPrefix(upload_type) + fileName;
					QRCodeUtilEx.createQrCodeImg(content,setMeal.getMealNo(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
					qrCode = img_key;
					setMeal.setQrCode(qrCode);
				}
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (setMealService.updateById(setMeal)) {
				return R.ok();
			}
		}
		return R.failed();
	}


	/**
     * 修改套餐列
     */
    @ApiOperation("修改套餐列")
    @PreAuthorize("@pms.hasPermission('module:meal:edit')")
    @SysLog("套餐列")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody SetMeal setMeal) {

		if(setMeal.getProvinceArray()!=null&&setMeal.getProvinceArray().length==2){
			setMeal.setProvId(Integer.parseInt(setMeal.getProvinceArray()[0]));
			setMeal.setCityId(Integer.parseInt(setMeal.getProvinceArray()[1]));

			Province province = provinceService.findById(setMeal.getProvinceArray()[0]);
			if(province!=null){
				setMeal.setProvName(province.getProvinceName());
			}

			City city = cityService.findById(setMeal.getProvinceArray()[1]);
			if(city!=null){
				setMeal.setCityName(city.getCityName());
			}
		}

        return R.okByRow(setMealService.updateById(setMeal) ? 1 : 0);
    }

    /**
     * 删除套餐列
     */
    @ApiOperation("删除套餐列")
    @PreAuthorize("@pms.hasPermission('module:meal:remove')")
    @SysLog("套餐列")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(setMealService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
